package edu.zjut.hjg.saas.web.interceptor;

import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_ADMIN;
import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_TENANT;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

import edu.zjut.hjg.saas.common.util.CookieSessionUtil;
import edu.zjut.hjg.saas.web.model.AdminSession;
import edu.zjut.hjg.saas.web.model.TenantSession;

/**
 * 把cookie session 放到请求属性中 <br />
 * 这个拦截器需要放到其它拦截器之前
 *
 * @author hjg
 */
public class SessionInterceptor implements WebRequestInterceptor {

    private CookieSessionUtil cookieSessionUtil;

    public void setCookieSessionUtil(CookieSessionUtil cookieSessionUtil) {
        this.cookieSessionUtil = cookieSessionUtil;
    }

    @Override
    public void preHandle(WebRequest request) throws Exception {
        if (request instanceof ServletWebRequest) {
            HttpServletRequest req = ((ServletWebRequest) request).getRequest();
            TenantSession tenantSession = cookieSessionUtil.getObjectFromCookieSession(
                    SESSION_NAME_TENANT, TenantSession.class, req);
            AdminSession adminSession = cookieSessionUtil.getObjectFromCookieSession(
                    SESSION_NAME_ADMIN, AdminSession.class, req);
            if (tenantSession != null) {
                request.setAttribute(SESSION_NAME_TENANT, tenantSession,
                        RequestAttributes.SCOPE_REQUEST);
            }
            if (adminSession != null) {
                request.setAttribute(SESSION_NAME_ADMIN, adminSession,
                        RequestAttributes.SCOPE_REQUEST);
            }
        }
    }

    @Override
    public void postHandle(WebRequest request, ModelMap model) throws Exception {
    }

    @Override
    public void afterCompletion(WebRequest request, Exception ex) throws Exception {
    }
}
